package com.cyy.demo.controller;

import com.cyy.demo.common.KafkaProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class KafkaController {

    @Autowired
    private KafkaProducer<String> kafkaProducer;

    @GetMapping("send-kafka")
    private String upload() {
        log.info("开始处理数据");
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ListenableFuture<SendResult<String, String>> result = kafkaProducer.send("test1");

        try {
            result.get(3, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.info("发送kafka失败: {}", e);
            return "发送kafka失败";

        }
        try {
            log.info("保存到数据库");
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        log.info("接口响应总时间:" + (System.currentTimeMillis() - start));
        return "ok";
    }
}